package com.example.springbootdemo.config;

import com.example.springbootdemo.exception.WorkIdGetException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * 获取服务器一些不同的配置
 *
 * @author wuzhen on 2021/4/14
 */
@Slf4j
public class ServerConfigProperties {
    public static Integer getWork() throws WorkIdGetException {
        // 获取配置文件
        YamlPropertiesFactoryBean yamlMapFactoryBean = new YamlPropertiesFactoryBean();
        //可以加载多个yml文件
        yamlMapFactoryBean.setResources(new ClassPathResource("application-common.yml"));
        Properties properties;
        try {
            properties = yamlMapFactoryBean.getObject();
        } catch (Exception e1) {
            log.error("配置文件读取失败");
            log.error("{}", e1.getMessage(), e1);
            throw new WorkIdGetException();
        }
        if (properties == null) {
            log.error("properties为null");
            throw new WorkIdGetException();
        }
        String content;
        try {
            content = new String(Files.readAllBytes(Paths.get(properties.getProperty("work.idPath"))), StandardCharsets.UTF_8);
        } catch (IOException e) {
            log.error("id文件读取失败");
            log.error("{}", e.getMessage(), e);
            throw new WorkIdGetException();
        }
        int workId;
        try {
            workId = Integer.parseInt(content.trim());
        }catch (Exception e){
            log.error("id文件内容不能转换为Int");
            log.error("{}", e.getMessage(), e);
            throw new WorkIdGetException();
        }
        log.info("worKId:" + workId);
        return workId;
    }
    public static Integer getWork(int defaultWorkId){
        int workerId;
        try {
            workerId = com.example.springbootdemo.config.ServerConfigProperties.getWork();
        } catch (Exception e) {
            log.error("获取workId失败 {}", e.getMessage(), e);
            //手动设置为1
            workerId = defaultWorkId;
        }
        return workerId;
    }
}
